package org.csu.question.controller;

import lombok.extern.slf4j.Slf4j;
import org.csu.question.entity.dto.AnswerResultDTO;
import org.csu.question.entity.dto.QuestionDTO;
import org.csu.question.entity.dto.SubmitAnswerRequest;
import org.csu.question.entity.dto.UserStatsDTO;
import org.csu.question.entity.po.KnowledgePoint;
import org.csu.question.entity.po.Questions;
import org.csu.question.mapper.KnowledgePointMapper;
import org.csu.question.mapper.QuestionMapper;
import org.csu.question.service.QuestionRecommendationService;
import org.csu.question.service.QuestionService;
import org.csu.question.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/questions")
@Slf4j
public class QuestionController {

    @Autowired
    private QuestionRecommendationService recommendationService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private KnowledgePointMapper knowledgePointMapper;
    /**
     * 获取推荐题目
     */
    @GetMapping("/recommend")
    public ApiResponse<List<QuestionDTO>> recommendQuestions(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "10") Integer count) {

        try {
            List<Questions> questions = recommendationService.recommendQuestions(userId, count);
            List<QuestionDTO> questionDTOs = questions.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());

            return ApiResponse.success(questionDTOs);
        } catch (Exception e) {
            log.error("推荐题目失败", e);
            return ApiResponse.error("推荐题目失败: " + e.getMessage());
        }
    }

    /**
     * 提交答案
     */
    @PostMapping("/submit")
    public ApiResponse<AnswerResultDTO> submitAnswer(@RequestBody SubmitAnswerRequest request) {
        try {
            AnswerResultDTO result = questionService.submitAnswer(request);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("提交答案失败", e);
            return ApiResponse.error("提交答案失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户答题统计
     */
    @GetMapping("/stats/{userId}")
    public ApiResponse<UserStatsDTO> getUserStats(@PathVariable Long userId) {
        try {
            UserStatsDTO stats = questionService.getUserStats(userId);
            return ApiResponse.success(stats);
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return ApiResponse.error("获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据标签获取题目
     */
    @GetMapping("/by-tag/{tag}")
    public ApiResponse<List<QuestionDTO>> getQuestionsByTag(@PathVariable String tag) {
        try {
            List<Questions> questions = questionMapper.selectByTag(tag);
            List<QuestionDTO> questionDTOs = questions.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());

            return ApiResponse.success(questionDTOs);
        } catch (Exception e) {
            log.error("根据标签获取题目失败", e);
            return ApiResponse.error("获取题目失败: " + e.getMessage());
        }
    }

    private QuestionDTO convertToDTO(Questions question) {
        QuestionDTO dto = new QuestionDTO();
        dto.setId(question.getId());
        dto.setTitle(question.getTitle());
        dto.setContent(question.getContent());
        dto.setOptions(question.getOptions());
        dto.setDifficulty(question.getDifficulty());

        // 查询知识点信息
        if (question.getKnowledgePointId() != null) {
            KnowledgePoint kp = knowledgePointMapper.selectById(question.getKnowledgePointId());
            if (kp != null) {
                dto.setKnowledgePointName(kp.getName());
                dto.setTag(kp.getTag());
            }
        }

        return dto;
    }
}
